package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cari.oa.domain.SysActionEntity;
import com.cari.oa.domain.SysModuleEntity;
import com.cari.oa.service.SysActionService;
import com.cari.oa.service.SysModuleService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.Utils;

@Controller
@SessionAttributes("username")
public class SysActionController {
	
	@Resource
	private SysActionService sysActionService;
	@Resource
	private SysModuleService sysModuleService;
	
	public static final String MODULE_NAME = "SYS_ACTION_MANAGE";
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
	}
	
    @RequestMapping("/system/action/list.do")
    public String list(String enname, String alias, String moduleName, Integer curPage, ModelMap modelMap) {
        if(curPage == null) curPage = 1;
        long totalRecords = sysActionService.getCount(enname, alias, moduleName);
        long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
        
        List<SysActionEntity> actionList = sysActionService.getPage(enname, alias, moduleName, curPage, Contants.PAGE_SIZE);
        List<SysModuleEntity> moduleList = sysModuleService.getAllSubModules();
        
        Map<String, String> mdNameMap = new HashMap<String, String>();
        for (SysModuleEntity sysModuleEntity : moduleList) {
			mdNameMap.put(sysModuleEntity.getEnname(), sysModuleEntity.getAlias());
		}

        modelMap.addAttribute("actionList", actionList);
        modelMap.addAttribute("moduleList", moduleList);
        modelMap.addAttribute("mdNameMap", mdNameMap);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);

        modelMap.addAttribute("enname", enname);
        modelMap.addAttribute("alias", alias);
        modelMap.addAttribute("moduleName", moduleName);

        return "system/action/list";
    }
    
    @RequestMapping(value = "/system/action/insert.do", method = RequestMethod.GET)
    public String enterInsert(String qs, ModelMap modelMap) {
        List<SysModuleEntity> moduleList = sysModuleService.getAllSubModules();
        modelMap.addAttribute("moduleList", moduleList);
        modelMap.addAttribute("qs", qs);
        return "system/action/insert";
    }

    @RequestMapping(value = "/system/action/view.do", method = RequestMethod.GET)
    public String enterView(String id, ModelMap modelMap) {
    	SysActionEntity action = sysActionService.getById(id);
    	SysModuleEntity module = sysModuleService.getModulesByEnname(action.getModuleName());
        modelMap.addAttribute("action", action);
        modelMap.addAttribute("module", module);
        return "system/action/view";
    }

    @RequestMapping(value = "/system/action/edit.do", method = RequestMethod.GET)
    public String enterEdit(String id, String qs, ModelMap modelMap) {
    	List<SysModuleEntity> moduleList = sysModuleService.getAllSubModules();
        SysActionEntity action = sysActionService.getById(id);
        modelMap.addAttribute("action", action);
        modelMap.addAttribute("moduleList", moduleList);
        modelMap.addAttribute("qs", qs);
        return "system/action/edit";
    }
    
    @RequestMapping(value = "/system/action/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public String postInsert(@ModelAttribute("username") String username, 
    		@Valid SysActionEntity actionEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());

        if (sysActionService.existByEnname(actionEntity.getEnname()))
            return Utils.errorJsonResp("系统操作英文名已存在");

        sysActionService.insert(actionEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增操作" + actionEntity.getEnname());
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/system/action/edit.do", method = RequestMethod.POST)
    @ResponseBody
    public String postEdit(@ModelAttribute("username") String username, 
    		@Valid SysActionEntity sysActionEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());

        sysActionService.update(sysActionEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "修改操作" + sysActionEntity.getEnname());
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/system/action/delete.do")
    @ResponseBody
    public String delete(@ModelAttribute("username") String username, String id) {
    	SysActionEntity sysActionEntity = sysActionService.getById(id);
        if(sysActionEntity == null) return Utils.errorJsonResp("该系统操作已不存在，请刷新页面");

        if(sysActionService.isActionUsedByRole(sysActionEntity.getEnname()))
            return Utils.errorJsonResp("还有角色关联该系统操作，请先解除关联，才能删除");

        sysActionService.delete(sysActionEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "删除操作" + sysActionEntity.getEnname());
        return Utils.normalJsonResp();
    }    
}
